// [DELETE]feature-t1-1.8.3-privilege
import React from 'react';
import { Form, Card, Button, Table, Select, message } from 'antd';
import { history } from 'umi'
// import { get as _get } from 'object-path';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { BottomAction } from '@/components';
import { hasWorkFlowByType } from '@/pages/WorkFlow/utils';
import TreeSelectPro from '@/components/TreeSelectPro/TreeSelectPro';
import pageTabUtil from '@/utils/pageTabUtil';

import { BaseWrapper } from '../components';
import { updateAuthToHistory, fetchDutyList } from '../services';
import { AUTH, GRADE } from '../constant';
// import styles from './index.less';

const { Option } = Select;

const getLocalRows = () => {
    const temp = localStorage.getItem('authEdit');
    if (temp) {
        const tempArr = JSON.parse(temp);
        return tempArr.map(({ children, ...rest }) => ({
            ...rest
        }));
    }
    return [];
};

const AuthEdit = ({ form }) => {
    const { getFieldDecorator } = form;
    const [rows] = React.useState(getLocalRows());
    const [loading, setLoading] = React.useState(false);
    const title = localStorage.getItem('authEditTitle') || '';

    const [treeData, setTreeData] = React.useState([]);
    const [treeDataLoading, setTreeDataLoading] = React.useState(false);
    const [treeSelectDataSource, setTreeSelectDataSource] = React.useState([]);

    const handleUpdate = async (arr = []) => {
        // 流程不存在提示
        const { workFlowUrl } = await hasWorkFlowByType('authManageApply');
        if (!workFlowUrl) {
            return;
        }

        setLoading(true);
        const newArr = arr.map(item => ({ ...item, operationType: 1 }));
        const result = await updateAuthToHistory(newArr);
        const { code, data, msg } = result;
        if (code === 10000) {
            history.push(`${workFlowUrl}${data}`);
        } else {
            message.error(msg);
        }
        setLoading(false);
    };

    const featchDutyCodes = async () => {
        setTreeDataLoading(true);
        const result = await fetchDutyList({ showTreeFlag: 1 });
        const { code, data, msg } = result;
        if (code === 10000) {
            setTreeData(data);
        } else {
            message.error(msg);
        }
        setTreeDataLoading(false);
    };

    const handleSubmit = () => {
        form.validateFieldsAndScroll((err, values) => {
            // console.log('handleSubmit -> values', values);
            if (!err) {
                // console.log('all');
                const { level, dutyCodes } = values;
                // console.log(rows);
                if (rows && rows.length > 0) {
                    const tempArr = [];
                    rows.forEach((item, index) => {
                        const { code, status, name, type } = item;
                        tempArr.push({
                            code,
                            status,
                            name,
                            type,
                            gradeType: level[index],
                            dutyCodes: dutyCodes[index]
                        });
                    });
                    console.log(tempArr);
                    handleUpdate(tempArr);
                }
            }
        });
    };

    const handleCancel = () => {
        pageTabUtil.goBack();
    };

    React.useEffect(() => {
        const filterDuties = tree =>
            tree.map(i => ({
                title: i.dutyAlias,
                value: i.dutyCode,
                key: i.dutyCode
            }));

        const filterTree = tree =>
            tree.map(({ children, organizationName, organizationCode, duties, ...props }) => {
                if ((children && children.length > 0) || (duties && duties.length > 0)) {
                    return {
                        children: [...filterTree(children), ...filterDuties(duties)],
                        title: organizationName,
                        value: organizationCode,
                        key: organizationCode,
                        disableCheckbox: false,
                        ...props
                    };
                }
                return {
                    children: '',
                    title: organizationName,
                    value: organizationCode,
                    key: organizationCode,
                    disableCheckbox: !!(!children?.length && !duties?.length),
                    ...props
                };
            });
        const result = filterTree(treeData);
        setTreeSelectDataSource(result);
    }, [treeData]);

    const columns = [
        {
            title: '功能',
            dataIndex: 'name',
            width: 200
        },
        {
            title: '类型',
            width: 100,
            dataIndex: 'type',
            render: text => AUTH[text] || ''
        },
        // {
        //     title: '简介',
        //     dataIndex: 'description',
        //     render: (text, record, index) => (
        //         <Form.Item style={{ margin: 0 }}>
        //             {getFieldDecorator(`desc[${index}]`, {
        //                 initialValue: text || ''
        //             })(<Input placeholder="请输入简介" allowClear maxLength={255} />)}
        //         </Form.Item>
        //     )
        // },
        {
            title: '等级',
            dataIndex: 'gradeType',
            width: 120,
            render: (text, record, index) => (
                <Form.Item style={{ margin: 0 }}>
                    {getFieldDecorator(`level[${index}]`, {
                        initialValue: record.gradeType,
                        placeholder: '请选择'
                    })(
                        <Select placeholder="请选择" style={{ width: '100%' }} getPopupContainer={node => node}>
                            {Object.keys(GRADE).map(item => (
                                <Option key={item} value={Number(item)}>
                                    {GRADE[item]}
                                </Option>
                            ))}
                        </Select>
                    )}
                </Form.Item>
            )
        },
        {
            title: '授权',
            dataIndex: 'dutyCodes',
            render: (text, record, index) => (
                <Form.Item style={{ margin: 0 }}>
                    {getFieldDecorator(`dutyCodes[${index}]`, {
                        initialValue: record.dutyCodes
                    })(
                        <TreeSelectPro
                            loading={treeDataLoading}
                            treeData={treeSelectDataSource}
                            getPopupContainer={node => node}
                            allowClear
                            treeCheckable
                            treeDefaultExpandedKeys={
                                treeSelectDataSource.length > 0 ? [treeSelectDataSource[0]?.key || ''] : []
                            }
                            style={{ width: '100%' }}
                            dropdownStyle={{ maxHeight: 300 }}
                            placeholder="请选择授权"
                            maxTagCount={5}
                        />
                    )}
                </Form.Item>
            )
        }
    ];

    React.useEffect(() => {
        featchDutyCodes();
    }, []);
    return (
        <PageHeaderWrapper>
            <Card
                title="权限变更申请"
                bordered={false}
                extra={
                    <BottomAction>
                        <Button onClick={handleCancel} style={{ marginRight: 8 }}>
                            取消
                        </Button>
                        <Button type="primary" loading={loading} onClick={handleSubmit}>
                            下一步
                        </Button>
                    </BottomAction>
                }
            >
                {/* <BaseWrapper title="变更理由">
                    <Form>
                        <Form.Item>
                            {getFieldDecorator('changeDesc')(
                                <TextArea placeholder="请输入变更理由" autosize={{ minRows: 3, maxRows: 6 }} />
                            )}
                        </Form.Item>
                    </Form>
                </BaseWrapper> */}
                <BaseWrapper title={`${title}变更内容`}>
                    <Table columns={columns} dataSource={rows} rowKey="id" pagination={false} />
                </BaseWrapper>
            </Card>
        </PageHeaderWrapper>
    );
};

export default Form.create({})(AuthEdit);
